﻿using MySql.Data.MySqlClient;
using System.Data;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApp1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        //mysql连接字符串
        private string connectionString = "server=localhost;user id=root;password=yuanlong;database=person";
        public MainWindow()
        {
            InitializeComponent();
        }

        //查询数据
        private void btnQuery_Click(object sender, RoutedEventArgs e)
        {
            //创建数据库连接
            using (MySqlConnection connection = new MySqlConnection(connectionString))
            {
                try
                {
                    connection.Open();
                    //创建查询命令
                    string sql = "SELECT * FROM person_info";
                    MySqlDataAdapter adapter = new MySqlDataAdapter(sql, connection);
                    //填充数据集
                    DataTable dataTable = new DataTable();
                    adapter.Fill(dataTable);
                    //绑定数据
                    dgvData.ItemsSource = dataTable.DefaultView;    
                    txtStatus.Text = $"查询成功,共{dataTable.Rows.Count}条数据";
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"查询失败：{ex.Message}","错误" , MessageBoxButton.OK, MessageBoxImage.Error );
                    txtStatus.Text = $"查询失败：{ex.Message}";
                    throw;
                }
            }
        }

        //添加数据
        private void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            string idText = txtId.Text.Trim();
            string nameText = txtName.Text.Trim();
            string ageText = txtAge.Text.Trim();
            if (string.IsNullOrEmpty(nameText))
            {
                MessageBox.Show("姓名不能为空", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            int age = 0;
            if(string.IsNullOrEmpty(ageText) &&!int.TryParse(ageText, out age)){
                MessageBox.Show("年龄必须为数字", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }
            try
            {
                using (MySqlConnection connection = new MySqlConnection(connectionString))
                {
                    connection.Open();
                    string sql = "INSERT INTO person_info(id,name,age) VALUES(@id,@name,@age)";
                    using MySqlCommand command = new MySqlCommand(sql, connection);
                    {
                        command.Parameters.AddWithValue("@id", idText);
                        command.Parameters.AddWithValue("@name", nameText);
                        command.Parameters.AddWithValue("@age", age);
                        int count = command.ExecuteNonQuery();
                        if (count > 0)
                        {
                            MessageBox.Show("添加成功", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                            txtStatus.Text = "添加成功";
                            btnQuery_Click(sender, e);
                        }
                        else
                        {
                            MessageBox.Show("添加失败", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                            txtStatus.Text = "添加失败";
                        }
                    }

                }
                  
            }catch(Exception ex)
            {
                MessageBox.Show($"添加失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                txtStatus.Text = $"添加失败：{ex.Message}";
            }
        }

        //更新数据
        private void btnUpdate_Click(object sender, RoutedEventArgs e)
        {
            if(dgvData.SelectedItems.Count == 0)
            {
                MessageBox.Show("请选择要更新的数据", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }
            DataRowView selectedrow = dgvData.SelectedItems[0] as DataRowView;
            if (selectedrow == null) return;
            string idText = txtId.Text.Trim();
            string nameText = txtName.Text.Trim();
            string ageText = txtAge.Text.Trim();
            if (string.IsNullOrEmpty(nameText))
            {
                MessageBox.Show("姓名不能为空", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            int age = 0;
            if (string.IsNullOrEmpty(ageText) &&!int.TryParse(ageText, out age))
            {
                MessageBox.Show("年龄必须为数字", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }
            try
            {
                using (MySqlConnection connection = new MySqlConnection(connectionString))
                {
                    connection.Open();
                    string sql = "UPDATE person_info SET name=@name,age=@age WHERE id=@id";
                    using (MySqlCommand command = new MySqlCommand(sql, connection))
                    {
                        command.Parameters.AddWithValue("@id", idText);
                        command.Parameters.AddWithValue("@name", nameText);
                        command.Parameters.AddWithValue("@age", age);
                        int count = command.ExecuteNonQuery();
                        if (count > 0)
                        {
                            txtStatus.Text = "更新成功";
                            ClearInputs();
                            btnQuery_Click(sender, e);
                        }
                        else
                        {
                            txtStatus.Text = "更新失败";
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"更新失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                txtStatus.Text = $"更新失败：{ex.Message}";
            }
        }

        //删除数据
        private void btnDelete_Click(object sender, RoutedEventArgs e)
        {
            if (dgvData.SelectedItems.Count == 0)
            {
                MessageBox.Show("请选择要删除的数据", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }
            if(MessageBox.Show("确认删除吗？", "提示", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.No)
            {
                return;
            }
            DataRowView selectedrow = dgvData.SelectedItems[0] as DataRowView;
            if (selectedrow == null) return;
            string idText = selectedrow["id"].ToString().Trim();
            try
            {
                using (MySqlConnection connection = new MySqlConnection(connectionString))
                {
                    connection.Open();
                    string sql = "DELETE FROM person_info WHERE id=@id";
                    using (MySqlCommand command = new MySqlCommand(sql, connection))
                    {
                        command.Parameters.AddWithValue("@id", idText);
                        int count = command.ExecuteNonQuery();
                        if (count > 0)
                        {
                            txtStatus.Text = "删除成功";
                            ClearInputs();
                            btnQuery_Click(sender, e);
                        }
                        else
                        {
                            txtStatus.Text = "删除失败";
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"删除失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                txtStatus.Text = $"删除失败：{ex.Message}";
            }
        }

        //清空输入框
        private void btnClear_Click(object sender, RoutedEventArgs e)
        {
            ClearInputs();
        }
        private void ClearInputs()
        {
            txtId.Text = "";
            txtName.Text = "";
            txtAge.Text = "";
        }

        //选中行时自动填入输入框
        private void dgvData_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (dgvData.SelectedItems.Count == 0)
            {
                return;
            }
            DataRowView selectedrow = dgvData.SelectedItems[0] as DataRowView;
            if (selectedrow == null) return;
            txtId.Text = selectedrow["id"].ToString().Trim();
            txtName.Text = selectedrow["name"].ToString().Trim();
            txtAge.Text = selectedrow["age"].ToString().Trim();
        }
    }
}